const config = require('../../../config');

// Test if potential opening or closing delimieter
// Assumes that there is a "$" at state.src[pos]
function isValidDelim(state, pos) {
    const prevChar = pos > 0 ? state.src.charCodeAt(pos - 1) : -1;
    const nextChar = pos + 1 <= state.posMax ? state.src.charCodeAt(pos + 1) : -1;

    let can_open = true, can_close = true;

    // 闭合符条件：前导字符为 空格/制表符/数字/左括号/转义符 时，禁止闭合
    if (
        prevChar === 0x20 || prevChar === 0x09 || // 空格或制表符
        (prevChar >= 0x30 && prevChar <= 0x39) || // 前导字符为数字（关键修改）
        (nextChar >= 0x30 && nextChar <= 0x39) || // 后继字符为数字
        nextChar === 0x28 || nextChar === 0xFF08 || // 后继字符为左括号
        (prevChar === 0x5C) // 前导字符为转义符（\）
    ) {
        can_close = false;
    }

    // 开启符条件：后续字符为 空格/制表符/右括号/句号/转义符 时，禁止开启
    if (
        nextChar === 0x09 || 
        nextChar === 0x29 || nextChar === 0xFF09 || // 右括号
        nextChar === 0x2E || nextChar === 0x3002 || // 句号
        (nextChar === 0x5C) // 后继字符为转义符（\）
    ) {
        can_open = false;
    }

    return { can_open, can_close };
}

function math_inline(state, silent) {
    if (state.src[state.pos] !== "$") return false;

    // 验证起始符合法性
    const openRes = isValidDelim(state, state.pos);
    if (!openRes.can_open) {
        if (!silent) state.pending += "$";
        state.pos++;
        return true;
    }

    // 寻找潜在闭合符
    let start = state.pos + 1;
    let match = start;
    while ((match = state.src.indexOf("$", match)) !== -1) {
        // 跳过转义符
        let pos = match - 1;
        while (state.src[pos] === "\\") pos--;
        if ((match - pos) % 2 === 1) break;
        match++;
    }

    if (match === -1) {
        if (!silent) state.pending += "$";
        state.pos = start;
        return true;
    }

    // 二次验证闭合符合法性（关键新增）
    const closeRes = isValidDelim(state, match);
    if (!closeRes.can_close) {
        if (!silent) state.pending += "$";
        state.pos = start;
        return true;
    }

    // 提取内容并处理转义符
    if (!silent) {
        const token = state.push('math_inline', 'math', 0);
        token.content = state.src.slice(start, match).replace(/\\\$/g, '$');
        token.markup = "$";
    }

    state.pos = match + 1;
    return true;
}

function math_block(state, startLine, endLine, silent) {
    // 检测起始行是否以 $$ 开头（允许缩进）
    const startPos = state.bMarks[startLine] + state.tShift[startLine];
    if (state.src.slice(startPos, startPos + 2) !== '$$') return false;

    // 寻找闭合标记 $$
    let endMarkerLine = -1;
    for (let line = startLine + 1; line < endLine; line++) {
        const lineStart = state.bMarks[line] + state.tShift[line];
        const lineEnd = state.eMarks[line];
        const lineText = state.src.slice(lineStart, lineEnd);
        
        // 严格匹配整行仅有 $$（允许前后空格）
        if (/^\s*\$\$\s*$/.test(lineText)) {
            endMarkerLine = line;
            break;
        }
    }

    if (endMarkerLine === -1) return false;

    if (silent) return true;

    // 提取公式内容（排除首尾 $$ 行）
    const content = state.getLines(startLine + 1, endMarkerLine - 1, 0, true)
                     .replace(/\\\$/g, '$'); // 处理转义符

    const token = state.push('math_block', 'math', 0);
    token.content = content.trim();
    token.map = [startLine, endMarkerLine];
    token.markup = '$$';
    token.block = true;

    state.line = endMarkerLine + 1; // 关键！跳过后续行
    return true;
}
// function math_block(state, start, end, silent){
//     var firstLine, lastLine, next, lastPos, found = false, token,
//         pos = state.bMarks[start] + state.tShift[start],
//         max = state.eMarks[start]

//     if(pos + 2 > max){ return false; }
//     if(state.src.slice(pos,pos+2)!=='$$'){ return false; }

//     pos += 2;
//     firstLine = state.src.slice(pos,max);

//     if(silent){ return true; }
//     if(firstLine.trim().slice(-2)==='$$'){
//         // Single line expression
//         firstLine = firstLine.trim().slice(0, -2);
//         found = true;
//     }

//     for(next = start; !found; ){

//         next++;

//         if(next >= end){ break; }

//         pos = state.bMarks[next]+state.tShift[next];
//         max = state.eMarks[next];

//         if(pos < max && state.tShift[next] < state.blkIndent){
//             // non-empty line with negative indent should stop the list:
//             break;
//         }

//         if(state.src.slice(pos,max).trim().slice(-2)==='$$'){
//             lastPos = state.src.slice(0,max).lastIndexOf('$$');
//             lastLine = state.src.slice(pos,lastPos);
//             found = true;
//         }

//     }

//     state.line = next + 1;

//     token = state.push('math_block', 'math', 0);
//     token.block = true;
//     token.content = (firstLine && firstLine.trim() ? firstLine + '\n' : '')
//     + state.getLines(start + 1, next, state.tShift[start], true)
//     + (lastLine && lastLine.trim() ? lastLine : '');
//     token.map = [ start, state.line ];
//     token.markup = '$$';
//     return true;
// }

module.exports = md => {
    var inlineRenderer = function(tokens, idx){
      return `<latex value="${encodeURIComponent(tokens[idx].content).replace(/'/g,'%27')}" type="line"></latex>`;
    };

    var blockRenderer = function(tokens, idx){
      return `<latex value="${encodeURIComponent(tokens[idx].content).replace(/'/g, '%27')}" type="block"></latex>`;
    };

    md.inline.ruler.after('escape', 'math_inline', math_inline);
    md.block.ruler.after('blockquote', 'math_block', math_block, {
        alt: [ 'paragraph', 'reference', 'blockquote', 'list' ]
    });
    md.renderer.rules.math_inline = inlineRenderer;
    md.renderer.rules.math_block = blockRenderer;
};